package com.ts.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ts.content.constants.RedisKeys;
import com.ts.content.entity.LikeEntity;
import com.ts.content.mapper.LikeMapper;
import com.ts.content.service.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;



@Service
public class LikeServiceImpl extends ServiceImpl<LikeMapper, LikeEntity> implements LikeService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    //点赞的业务
    @Override
    public void addCollection(LikeEntity likeEntity) {
        SetOperations<String, String> setOperations = redisTemplate.opsForSet();
        //准备key
        String likeKey = String.format(RedisKeys.USER_LIKE, likeEntity.getEntityType(), likeEntity.getEntityId());
        String userKey = String.format(RedisKeys.User_LIKE_COUNT, likeEntity.getUserId());

        //判断当前用户是否对该帖子点赞过了
        Boolean member = setOperations.isMember(likeKey, likeEntity.getUserId().toString());
        if (member){
            //如果点赞过了就删除
            setOperations.remove(likeKey,likeEntity.getUserId().toString());
        }else {
            //没点赞过加加入
            setOperations.add(likeKey,likeEntity.getUserId().toString());
        }
    }

    //查询当前用户是否点赞
    public Boolean isLike(Integer type, Integer topicId, Integer userId){
        //获取点赞的key
        String likeKey = String.format(RedisKeys.USER_LIKE, type, topicId);
        //判断是否点赞
        SetOperations<String, String> SetOperations = redisTemplate.opsForSet();
        return SetOperations.isMember(likeKey, userId.toString());
    }

    //查询当前帖子点赞数
    public Long likeCount(Integer type,Integer postId){
        String likeKey = String.format(RedisKeys.USER_LIKE, type, postId);
        SetOperations<String, String> stringStringSetOperations = redisTemplate.opsForSet();
        return stringStringSetOperations.size(likeKey);
    }
}
